import io from "socket.io-client";
import { useCallback, useEffect, useState, useMemo } from "react";

type UseSocket = [connectState: boolean, enterGame: (name: string) => void];

const useSocket = (): UseSocket => {
  const socket = useMemo(
    () => io("https://localhost:3000", { reconnection: false }),
    []
  );
  const [connectState, setConnectState] = useState(false);

  const listenWelcome = useCallback(() => {
    //监听服务端的消息
    socket.on("welcome", msg => {
      console.log(msg);
    });
  }, [socket]);

  const handleConnect = useCallback(() => {
    //连接成功
    socket.on("connect", () => {
      console.log("connect success👏");
      setConnectState(socket.connected); //true
      listenWelcome();
    });

    //报错时走这个方法
    socket.on("connect_error", (error: any) => {
      console.error("🥶connect_error:", error);
    });
  }, [listenWelcome, socket]);

  useEffect(() => {
    handleConnect();
  }, [handleConnect]);

  const enterGame = useCallback(
    (name: string) => {
      socket.emit("enter", name);
    },
    [socket]
  );

  return [connectState, enterGame];
};

export default useSocket;
